// pages/mch/order/delivery.js
const App = getApp()
import Qiniu from '../../../utils/qiniu'
import Kits from '../../../utils/kits'
import Util from '../../../utils/util'

Page({
  data: {
    init: false,
    order: {},

    vinfo: '',
    vcode: '',
    mile: '',
    thing: '',
    photo: [],
    video: [],
    detail: [],


    butText: '获取验证码',
    butDisabled: false,
    interval: undefined,
    sec: 0,


    oilOpts: [{
      id: 1,
      name: '1 / 8'
    }, {
      id: 2,
      name: '2 / 8'
    }, {
      id: 3,
      name: '3 / 8'
    }, {
      id: 4,
      name: '4 / 8'
    }, {
      id: 5,
      name: '5 / 8'
    }, {
      id: 6,
      name: '6 / 8'
    }, {
      id: 7,
      name: '7 / 8'
    }, {
      id: 8,
      name: '8 / 8'
    }],
    oilIndex: 1,
    showUserInfo: false,
  },
  onLoad(options) {
    this.execLoad(options.oid)
  },
  onUnload() {
    if (this.data.interval != undefined) {
      clearInterval(this.data.interval)
    }
  },
  execLoad(oid) {
    App.doPost({
      uri: '/app/merchant/order/detail',
      body: {
        id: oid
      },
      fnSucc: resp => {
        resp.data.deposit.totalStr = Kits.fmtMoneyString(resp.data.deposit.total)
        resp.data.rent.totalStr = Kits.fmtMoneyString(resp.data.rent.total)
        resp.data.rent.paidStr = Kits.fmtMoneyString(resp.data.rent.paid)
        if(resp.data.begin){
          resp.data.beginStr = this.formatCurrentYearTime(resp.data.begin)
        }
        if(resp.data.close){
          resp.data.closeStr = this.formatCurrentYearTime(resp.data.close)
        }
        this.setData({
          init: true,
          order: resp.data,
        })
      }
    })
  },

  execGetVcode() {

    if (this.data.butDisabled) {
      return
    }
    this.setData({
      loading: true,
      butDisabled: true
    })
    App.doPost({
      uri: '/app/base/tool/sms/captcha',
      body: {
        mob: this.data.order.customer.phone
      },
      fnSucc: resp => {
        this.setData({
          sec: resp.data.limit,
          vinfo: resp.data.vinfo,
        })
        let int = setInterval(() => {
          if (this.data.sec <= 1) {
            clearInterval(this.data.interval)
            this.setData({
              sec: 0,
              butText: '验证码',
              butDisabled: false,
              interval: undefined
            })
            return
          }
          this.data.sec = this.data.sec - 1
          this.setData({
            sec: this.data.sec,
            butText: `${this.data.sec} 秒后重发`
          })
        }, 1000);
        this.setData({
          interval: int
        })
        if (App.Global.Debug && resp.data.vcode) {
          wx.showToast({
            icon: 'none',
            title: '测试账号，验证码已自动填写'
          })
          this.setData({
            vcode: resp.data.vcode
          })
        } else {
          wx.showToast({
            title: '验证码已发送'
          })
        }

      },
      fnFail: resp => {
        Util.Notify.error(`[${resp.stat.err}] ${resp.stat.msg}`)
        this.setData({
          butDisabled: false,
        })
      },
      fnComp: () => {
        this.setData({
          loading: false,
        })
      }
    })
  },

  doChooseItem(e) {
    let type = e.currentTarget.dataset.type
    wx.chooseMedia({
      count: 1,
      mediaType: [type == 'video' ? 'video' : 'image'],
      sourceType: ['album', 'camera'],
      sizeType: ['original', 'compressed'],
      maxDuration: 60,
      camera: 'back',
      success: (res) => {
        this.execUpload(res.tempFiles[0].tempFilePath, type)
      }
    })
  },
  execUpload(path, type) {
    App.doPost({
      uri: '/comm/tool/file/qiniu/info',
      body: {
        type: type == 'video' ? 'Video' : 'Image'
      },
      fnSucc: resp => {
        let key = resp.data.path + resp.data.fileid + '.' + path.split('.').pop()?.toLowerCase()
        Qiniu.upload(path, (res) => {
          if (type == 'photo') {
            let srcs = this.data.photo
            srcs[srcs.length] = res.imageURL
            this.setData({
              photo: srcs
            })
          }
          if (type == 'video') {
            let srcs = this.data.video
            srcs[srcs.length] = res.imageURL
            this.setData({
              video: srcs
            })
          }
          if (type == 'detail') {
            let srcs = this.data.detail
            srcs[srcs.length] = res.imageURL
            this.setData({
              detail: srcs
            })
          }
        }, (err) => {
          console.log(err)
        }, {
          region: 'NCN',
          key: key,
          uptoken: resp.data.token,
          uptokenFunc: null,
          uptokenURL: null,
          domain: resp.data.domain,
          shouldUseQiniuFileName: false,
        }, () => {

        }, () => {

        })
      },
      fnFail: resp => {
        App.doAlert('出错啦', `上传失败，[${resp.stat.err}] ${resp.stat.msg}`)
      }
    })
  },
  doPreviewItem(e) {
    let type = e.currentTarget.dataset.type
    let sources = []

    this.data[type].forEach(p => {
      sources[sources.length] = {
        url: p,
        type: type == 'video' ? 'video' : 'image'
      }
    })

    let current = this.data[type].findIndex(p => p == e.currentTarget.dataset.url)
    console.log(sources, current)
    wx.previewMedia({
      sources: sources,
      current: current
    })
  },
  doDeleteItem(e) {
    if (e.currentTarget.dataset.type == 'photo') {
      this.data.photo.splice(e.currentTarget.dataset.index, 1);
      this.setData({
        photo: this.data.photo
      })
    }
    if (e.currentTarget.dataset.type == 'video') {
      this.data.video.splice(e.currentTarget.dataset.index, 1);
      this.setData({
        video: this.data.video
      })
    }
    if (e.currentTarget.dataset.type == 'detail') {
      this.data.detail.splice(e.currentTarget.dataset.index, 1);
      this.setData({
        detail: this.data.detail
      })
    }

  },
  doPreviewIdc(e) {
    let index = e.currentTarget.dataset.index
    let sources = []

    sources.push({
      url: this.data.order.picker.idc.pica,
      type: 'image'
    })

    sources.push({
      url: this.data.order.picker.idc.picb,
      type: 'image'
    })

    wx.previewMedia({
      sources: sources,
      current: index
    })
  },
  doPreviewDlc(e) {
    let index = e.currentTarget.dataset.index
    let sources = []

    sources.push({
      url: this.data.order.picker.dlc.pica,
      type: 'image'
    })

    sources.push({
      url: this.data.order.picker.dlc.picb,
      type: 'image'
    })

    wx.previewMedia({
      sources: sources,
      current: index
    })
  },
  doOilChange(e) {
    console.log('1121', e.detail.value)
    this.setData({
      oilIndex: e.detail.value
    })
  },
  doChangeOilSlider(e){
    console.log(e.detail.value)
    this.setData({
      oilIndex: e.detail.value
    })
  },
  execSave() {
    if (!this.data.order.rent.paid && this.data.order.rent.other_plat_paid !== this.data.order.rent.total) {
      Util.Notify.warn(`未支付租金无法交车`)
      return
    }
    if (!this.data.order.deposit.paid) {
      Util.Notify.warn(`未支付押金无法交车`)
      return
    }

    if (!this.data.vinfo) {
      Util.Notify.warn(`请获取验证码`)
      return
    }
    if (!this.data.vcode) {
      Util.Notify.warn(`请填写验证码`)
      return
    }

    if (!this.data.mile) {
      Util.Notify.warn(`请填写行驶里程`)
      return
    }
    if (this.data.photo.length == 0 && this.data.video.length == 0) {
      Util.Notify.warn(`请上传验车图片或视频`)
      return
    }

    this.setData({
      loading: true
    })
    App.doPost({
      uri: '/app/merchant/order/delivery',
      body: {
        id: this.data.order.id,
        captcha: {
          info: this.data.vinfo,
          code: this.data.vcode
        },
        info: {
          mile: parseInt(this.data.mile),
          fuel: parseInt(this.data.oilIndex),
          thing: this.data.thing
        },
        photo: this.data.photo,
        video: this.data.video,
        detail: this.data.detail
      },
      fnSucc: () => {
        wx.pub("ReloadOrderList", {})
        Util.Toast.succ(`交车成功`)

        setTimeout(() => {
          wx.redirectTo({
            url: '/pages/mch/order/sign?oid=' + this.data.order.id,
          })
        }, 1000);
      },
      fnFail: resp => {
        Util.Notify.error(`[${resp.stat.err}] ${resp.stat.msg}`)
      },
      fnComp: () => {
        this.setData({
          loading: false,
        })
      }
    })
  },
  doChange() {
    Util.Notify.warn(`暂不可调整租期`)

  },
  showUserInfoMet() {
    this.setData({
      showUserInfo: !this.data.showUserInfo
    })
  },
  formatCurrentYearTime (time) {
    const date = new Date(time)
    const now = new Date()
    if (date.getFullYear() === now.getFullYear()) {
      return date.format('MM-dd HH:mm')
    } else {
      return date.format('yyyy-MM-dd HH:mm')
    }
  },
})